package com.doodod.common.utils;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * User: 邱孝兵
 * Date: 14-2-28
 * Time: 上午4:31
 * To change this template use File | Settings | File Templates.
 */

public class BeanUtilsBean {

    /**
     * 该静态方法用于将BO转变成Map,key为属性名,value为属性值,便于解析
     * 使用Introspector反射得到bean基本信息。
     * 使用method的invoke方法得到property的值。
     * @param bean
     * @return
     */
	public static Map<String, Object> describe(Object bean)
			throws IntrospectionException, IllegalAccessException,
			IllegalArgumentException, InvocationTargetException {
		if (bean == null) {
			return (new HashMap<String, Object>());
		}
		BeanInfo info = Introspector.getBeanInfo(bean.getClass());
		Map<String, Object> description = new HashMap<String, Object>();
		PropertyDescriptor[] descriptors = info.getPropertyDescriptors();
		for (int i = 0; i < descriptors.length; i++) {
			String name = descriptors[i].getName();
			Method reader = descriptors[i].getReadMethod();
			if (reader != null) {
				Object[] os = new Object[0];
				Object value = reader.invoke(bean, os);
				description.put(name, value);
			}
		}
		description.remove("class");
		return description;
	}
}